package com.example.web.servlet;

import com.example.common.Result;
import com.example.model.Order;
import com.example.model.User;
import com.example.service.OrderService;
import com.example.service.impl.OrderServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/order")
public class OrderServler extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        Result result = null;
        if (user == null) {
            // 用户没有登录
            result = Result.fail(300 , "请先登录");
            String result_str = objectMapper.writeValueAsString(result);
            resp.getWriter().write(result_str);
            return;
        }
        List<Order> orders = orderService.findAll(user.getUid());
        result = Result.success(orders);
        String result_str = objectMapper.writeValueAsString(result);
        resp.getWriter().write(result_str);
    }
}
